import React, { useState, useEffect } from 'react';
import { NavBar, TabBar } from 'antd-mobile';
import { useUserContext } from '@/context/UserContext';
import { NestedRouteProvider } from '@/context/NestedRouteContext';

import {
  Outlet,
  useNavigate,
  useLocation,
  MemoryRouter as Router,
} from 'react-router-dom';
import {
  AppOutline,
  MessageOutline,
  UnorderedListOutline,
  UserOutline,
} from 'antd-mobile-icons';
import styles from './MainLayout.module.scss';

const Bottom = ({ setTitle }) => {
  const navigate = useNavigate();
  const location = useLocation();
  const { configDefault, recordRouteName, getRouteName } = useUserContext();
  // console.log('userState',userState);
  const { pathname } = location;
  const [activeKey, setActiveKey] = useState(configDefault.tabDefault);




  useEffect(() => {
    const routeName = getRouteName();
    if (routeName&&routeName.includes('/detail')) {
      setRouteActive('charts')
    }else if (location.pathname.includes('/home')) {
      setRouteActive('home')
    }else if (location.pathname.includes('/charts')) {
      setRouteActive('charts')
    }else if (location.pathname.includes('/mine')) {
      setRouteActive('mine')
    }else{
      setRouteActive(location.state ? location.state : configDefault.tabDefault)
    }
    recordRouteName(pathname);//记录路由
  }, [])

  const setRouteActive = (value) => {
    navigate(value, { state: { preserveState: true } });
    setTitle(tabs.find((item) => item.key === value).title);
    setActiveKey(value);
  };

  const tabs = [
    {
      key: 'home',
      title: '新增',
      icon: <AppOutline />,
    },
    {
      key: 'charts',
      title: '文章',
      icon: <MessageOutline />,
    },
    {
      key: 'mine',
      title: '我的',
      icon: <UserOutline />,
    },
  ];

  return (
    <TabBar style={{ height: configDefault.styles['--adm-tab-bar-height'], backgroundColor: '#fff', borderTop: "1px solid #E0E0E0" }} activeKey={pathname} onChange={(value) => setRouteActive(value)}>
      {tabs.map((item) => (
        <TabBar.Item style={activeKey === item.key ? { color: configDefault.styles['--adm-tab-bar-item-active-color'] } : { color: configDefault.styles['--adm-tab-bar-item-color'] }} key={item.key} icon={item.icon} title={item.title} />
      ))}
    </TabBar>
  );
};


const MainLayout = () => {
  const [title, setTitle] = useState('标题');

  return (
    <NestedRouteProvider>
      <div className={styles.app}>
        <div className={styles.top}>
          {/* <NavBar>配合路由使用</NavBar> */}
          <NavBar backIcon={false}>
            {title}
          </NavBar>
        </div>
        <div className={styles.body}>
          {/* 二级路由出口 */}
          <Outlet />
        </div>
        <div className={styles.bottom}>
          <Bottom setTitle={setTitle} />
        </div>
      </div>
    </NestedRouteProvider>
  );
};

export default MainLayout;
